package com.zhzh.sc.demo.proxy.cglib;

import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.objenesis.Objenesis;
import org.springframework.objenesis.ObjenesisStd;

public class ProxyFactory {

    private static ProxyFactory instance = new ProxyFactory();

    public static ProxyFactory getProxyInstance() {
        return instance;
    }

    public static <T> T getProxyInstance(Class<T> cls) {
        // 构建增强器
        Enhancer enHancer = new Enhancer();
        //需要传入具体的cglib动态代理回调处理类
        enHancer.setCallback(SimpleMethodInterceptor.getInstance());
        enHancer.setSuperclass(cls);
        return (T) enHancer.create();
    }

    public static <T> T getProxyInstance2(Class<T> cls) {
        // 构建增强器
        Enhancer enHancer = new Enhancer();
        // 设置父类
        enHancer.setSuperclass(cls);
        //需要传入具体的cglib动态代理回调处理类
        enHancer.setCallbackType(SimpleMethodInterceptor.class);
        // 创建代理类
        Class proxyClass = enHancer.createClass();
        // 给类中注册拦截回调
        Enhancer.registerCallbacks(proxyClass, new Callback[]{SimpleMethodInterceptor.getInstance()});
        // 针对构造不做拦截
        enHancer.setInterceptDuringConstruction(false);
        Objenesis objenesis = new ObjenesisStd(true);
        return (T) objenesis.newInstance(proxyClass);
    }

}
